import React from 'react';
import { Spin, Checkbox } from 'antd';

/**
 * 多选框组
 */
function CheckboxGroup(props) {
    const {
        labelInValue,
        labelKey = 'lable',
        valueKey = 'value',
        loading,
        options = [],
        value = [],
        onChange = () => {},
    } = props;

    if (loading) return <Spin />;

    return (
        <div style={{ display: 'inline-flex', flexDirection: 'column', padding: '10px 0 10px 10px' }}>
            <div style={{ paddingBottom: 10 }}>
                <Checkbox
                    indeterminate={value.length && value.length < options.length}
                    checked={value.length && value.length === options.length}
                    disabled={!options.length}
                    onChange={(e) => {
                        onChange(
                            e.target.checked ? options.map((option) => (labelInValue ? option : option[valueKey])) : []
                        );
                    }}
                >
                    全选
                </Checkbox>
            </div>
            <div>
                {options.map((option) => (
                    <Checkbox
                        key={option[valueKey]}
                        checked={
                            labelInValue
                                ? value.findIndex(({ [valueKey]: value }) => value === option[valueKey]) !== -1
                                : value.includes(option[valueKey])
                        }
                        onChange={(e) => {
                            onChange(
                                e.target.checked || value.length === options.length
                                    ? [labelInValue ? option : option[valueKey]]
                                    : []
                            );
                        }}
                    >
                        {option[labelKey]}
                    </Checkbox>
                ))}
            </div>
        </div>
    );
}

export default CheckboxGroup;
